<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\Statistic
 *
 * @method static \Database\Factories\StatisticFactory factory(...$parameters)
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic query()
 * @mixin \Eloquent
 * @property int $id
 * @property string|null $title
 * @property string $value
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Statistic whereValue($value)
 */
class Statistic extends Model
{
	use HasFactory;
	
	protected $guarded = ['id'];
	
	public static function isDenied()
	{
		$goldRounds = GoldRound::allAvailable();
		
		if ($goldRounds->isEmpty()) return false;
		
		$currentTime = Carbon::now()->second(0)->toDateTimeString();
		
		foreach ($goldRounds as $round) {
			
			if ($round['today_opened_at'] == $currentTime) {
				return true;
			}
			if ($round['today_started_at'] == $currentTime) {
				return true;
			}
		}
		
		return false;
	}
	
	public static function rewrite($title, $value)
	{
		$statistic = self::firstOrCreate(['title' => $title]);
		if ($value != $statistic->value) {
			$statistic->update(['value' => $value]);
		}
		return $statistic;
	}
	
	public static function fetch($title)
	{
		return self::firstOrCreate(['title' => $title])->value;
	}
}
